import 'package:custom_refresh_indicator/custom_refresh_indicator.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:air_puff/mvp/base_page.dart';
import 'package:air_puff/mvp/power_presenter.dart';
import 'package:air_puff/pages/map/iviews/one_city_ivews.dart';
import 'package:air_puff/pages/map/presenter/one_city_presenter.dart';
import 'package:air_puff/pages/map/provider/one_city_provider.dart';

class CityAirQualityPage extends StatefulWidget {
  const CityAirQualityPage({Key? key}) : super(key: key);

  @override
  State<CityAirQualityPage> createState() => _CityAirQualityPageState();
}

class _CityAirQualityPageState extends State<CityAirQualityPage>
    with
        SingleTickerProviderStateMixin,
        AutomaticKeepAliveClientMixin<CityAirQualityPage>,
        BasePageMixin<CityAirQualityPage, PowerPresenter<dynamic>>
    implements OneCityIMvpView {
  @override
  void initState() {
    super.initState();
    provider.cityNameController.text = '青岛';
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getCityAirQualityData();
    });
  }

  @override
  void dispose() {
    super.dispose();
    provider.cityNameController.dispose();
  }

  Future<void> getCityAirQualityData() async {
    _oneCityPresenter.getCityAirQualityData(provider.cityNameController.text);
  }

  late OneCityPresenter _oneCityPresenter;

  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter =
    PowerPresenter<dynamic>(this);
    _oneCityPresenter = OneCityPresenter();
    powerPresenter.requestPresenter([_oneCityPresenter]);
    return powerPresenter;
  }

  @override
  OneCityProvider provider = OneCityProvider();

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ChangeNotifierProvider<OneCityProvider>(
        create: (_) => provider,
        child: Consumer<OneCityProvider>(builder: (_, provider, __) {
          return Scaffold(
            appBar: AppBar(
              title: const Align(
                child: Text(
                  '空气质量',
                  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25),
                ),
              ),
              backgroundColor: Colors.blue[200],
            ),
            body: CustomMaterialIndicator(
              onRefresh: getCityAirQualityData,
              indicatorBuilder:
                  (BuildContext context, IndicatorController controller) {
                return const Icon(
                  Icons.ac_unit,
                  color: Colors.blue,
                  size: 30,
                );
              },
              child: ListView(
                children: [
                  Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      /// 上半部分展示
                      children: [
                        Padding(
                          padding: const EdgeInsets.all(8),
                          child: Row(
                            children: [
                              Expanded(
                                child: Container(
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                          width: 2, color: Colors.grey),
                                      borderRadius: BorderRadius.circular(10)),
                                  child: TextField(
                                    controller: provider.cityNameController,
                                    onSubmitted: (value) {
                                      getCityAirQualityData();
                                    },
                                    decoration: const InputDecoration(
                                        icon: Padding(
                                          padding: EdgeInsets.all(3),
                                          child: Icon(Icons.search,
                                              color: Colors.grey),
                                        ),
                                        border: InputBorder.none,
                                        contentPadding: EdgeInsets.all(3),
                                        hintText: '请输入城市名',
                                        counterText: ""),
                                  ),
                                ),
                              ),
                              const SizedBox(width: 15),
                              SizedBox(
                                  width: 100,
                                  height: 30,
                                  child: FilledButton(
                                    onPressed: () {
                                      getCityAirQualityData();
                                    },
                                    child: const Align(
                                      child: Text('搜索'),
                                    ),
                                  ))
                            ],
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Card(
                              color: Colors.blue[50],
                              child: SizedBox(
                                width: 120,
                                height: 120,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Text(
                                      (provider.airModel?.aqi ?? 0).toString(),
                                      style: const TextStyle(fontSize: 50),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            Card(
                                elevation: 4.0,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(8.0),
                                ),
                                child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Column(
                                    children: [
                                      airQualityIndex(
                                          'O3',
                                          (provider.airModel?.iaqi?.o3?.v ?? 0)
                                              .toString()),
                                      const SizedBox(height: 10),
                                      airQualityIndex(
                                          'PM2.5',
                                          (provider.airModel?.iaqi?.pm25?.v ??
                                              0)
                                              .toString()),
                                      const SizedBox(height: 10),
                                      airQualityIndex(
                                          'SO2',
                                          (provider.airModel?.iaqi?.so2?.v ?? 0)
                                              .toString()),
                                      const SizedBox(height: 10),
                                      airQualityIndex(
                                          'NO2',
                                          (provider.airModel?.iaqi?.no2?.v ?? 0)
                                              .toString()),
                                    ],
                                  ),
                                )),
                          ],
                        ),
                        const SizedBox(height: 20),
                        const Align(
                          child: Text('Suggestions',
                              style: TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 25)),
                        ),
                        const SizedBox(height: 8),
                        Column(
                          children: [
                            Card(
                              elevation: 4.0,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                              child: Padding(
                                padding: const EdgeInsets.all(10),
                                child: Text(
                                  getSuggestions((provider.airModel?.aqi ?? 0)),
                                  maxLines: 15,
                                  overflow: TextOverflow.ellipsis,
                                  // textAlign: TextAlign.center,
                                  style:
                                  const TextStyle(fontSize: 16, height: 2),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        }));
  }

  /// 每一行空气质量的样式
  Widget airQualityIndex(String name, String count) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        SizedBox(width: 70, child: Text(name)),
        Container(
          width: 25,
          height: 25,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Colors.lightBlue[400], // 设置圆圈的颜色
          ),
        ),
        const SizedBox(width: 8),
        SizedBox(
          width: 70,
          child: Text(
            count,
          ),
        )
      ],
    );
  }

  String getSuggestions(int aqi) {
    if (aqi >= 0 && aqi <= 50) {
      return "优:\n  空气质量被认为非常好。这种水平的空气纯度意味着与空气污染有关的风险很小或没有风险。\n户外活动指南：\n   所有的户外活动，如慢跑、骑自行车和野餐，都可以进行，不用担心空气质量。";
    } else if (aqi >= 51 && aqi <= 100) {
      return "良:\n  空气质量良好;然而，对于某些污染物，对空气污染异常敏感的极少数人可能会有中等程度的健康问题。\n户外活动指南：\n   大多数人都能参加户外活动。那些敏感的人，比如有某些疾病的人，应该考虑限制高强度的户外运动和长时间暴露在室外空气中。";
    } else if (aqi >= 101 && aqi <= 150) {
      return "一般:\n  敏感的个人可能会受到空气污染的更严重影响，这可能导致健康问题，但一般公众不太可能受到影响。\n户外活动指南：\n   儿童、老人、心血管或呼吸系统疾病患者等高危人群应限制户外运动。一般人应该考虑减少户外体育活动，以减少接触空气污染物。";
    } else if (aqi >= 151 && aqi <= 200) {
      return "轻度污染:\n  空气质量较差，每个人的健康都可能受到影响;敏感群体的成员可能会发现这些影响更为明显。\n户外活动指南：\n   包括儿童、老人在内的弱势群体，以及患有心肺疾病的人，应避免剧烈活动和户外运动。其他人应该减少高强度的户外活动。";
    } else if (aqi >= 201 && aqi <= 300) {
      return "重度污染:\n  空气质量很差，对每个人的身体健康都会造成影响。\n户外活动指南：\n   建议敏感人群呆在室内，避免一切身体活动。不敏感的人也应该呆在室内，尽可能减少所有户外活动。";
    } else if (aqi >= 301 && aqi <= 500) {
      return "极度污染:\n  此时空气质量空前的差，此时应该会有国家级预警，对所有人的健康都会造成极大的危害。\n户外活动指南：\n   所有人，无论健康状况如何，都应留在室内，保持门窗关闭，避免体力消耗。在这些危险条件下，使用空气净化器可以帮助减少室内空气污染。";
    } else {
      return "数据解析错误!";
    }
  }

  @override
  bool get wantKeepAlive => true;
}
